package com.nami.client.network.codec;


import com.nami.basic.packet.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-14 13:20
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class WsMessageEncoder extends MessageToMessageEncoder<Packet> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, List<Object> out) throws Exception {
        if (null == packet) {
            log.info("[netty] packet was null");
            return;
        }
        if ((byte) 0 == packet.getCmd()) {
            log.info("[netty] cmd is null");
            return;
        }

        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeByte((byte) 8);
        // 写入cmd 1 字节
        byteBuf.writeInt(packet.getCmd());
        // 版本 1字节
        byteBuf.writeByte(packet.getVersion());
        // 加密类型 1字节
        byteBuf.writeByte(packet.getEncrypt());
        // 序列化类型 1字节
        byteBuf.writeByte(packet.getSerial());
        // 包长度 4字节
        byteBuf.writeInt(packet.getLength());
        // 写入数据
        byteBuf.writeBytes(packet.getBody());
//        log.info("[nami-encode] 写入byteBuf use:{}ms", System.currentTimeMillis() - startTime);
        out.add(new BinaryWebSocketFrame(byteBuf));
    }
}
